/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 标题 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) { PAR = $.par } else if ($.hasOwnProperty('script_parameter')){ PAR = JSON.parse($.script_parameter); }
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({ table: "pdm_aimdfm_task", data: { current_process_title: $.process_title }, where: { id: $.task_id } });
	}
}
var Status = 'ok';
var resultData = [];
var par = PAR;
var default_par = {
	// step2:"unit",
    step: "unit.*",
	auto_save: "No",
	units:"mm"
}
for(var key in default_par){ if (!par.hasOwnProperty(key) || par[key] == ""){ par[key] = default_par[key] }}
var job = Job;
try {
	if(_.isEmpty(job)){throw "参数job不存在"} else { job = job.toLowerCase() }
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){ if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" } else { GEN.checkInout({job:job,mode:"out"}) } }
	var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig")
		return reg.test(step)
	})
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}

	var drl_slot_tmp = "drl_slot_tmp";
	var drl_pre1 = "drl_pre1";
	var drl_pre2 = "drl_pre2";
	var drl_pre3 = "drl_pre3";
	var drl_pre4 = "drl_pre4";

	var layers_tmp = [drl_slot_tmp,drl_pre1,drl_pre2,drl_pre3,drl_pre4]	

	var matrix = GEN.getMatrix({job:job})

	var drls = Object.keys(matrix).filter(function(key){
		var info = matrix[key];
		return /^drl\d*/.test(info.name) && info.context == "board" 
	})

	var units = par.units;
	stepList.forEach(function(step){
        GEN.openStep({job:job,name:step})
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units }); 
		GEN.zoomHome(); 

		drls.forEach(function(drl){
			delIfExist(layers_tmp)
		// 1. 钻孔分离到辅助层   槽长槽宽比 <= 1.8  拷贝到 drl_slot_tmp
		// 2. 4050 <= r <= 5050  拷贝到 drl_pre1
		// 3. 5100 <= r <= 6000  drl_pre2
		// 4. 6050 <= r <= 9000  drl_pre3
		// 5. 9050 <= r <= 12000  drl_pre4
        GEN.workLayer({name:drl,display_number:2,clear_before:'yes'})
		GEN.selectByFilter({attribute:[{attribute:".string", text:"_pre_drl"}]})
        if(GEN.getSelectCount() > 0) {
            IKM.msg("已经存在预钻孔,是否删除重新制作")
            GEN.PAUSE("check")
            GEN.workLayer({name:drl,display_number:2,clear_before:'yes'})
            GEN.selectByFilter({attribute:[{attribute:".string", text:"_pre_drl"}]})
            if(GEN.getSelectCount() > 0) { GEN.selDelete() }
        }
		GEN.selectByFilter({feat_types:"line"})
		if(GEN.getSelectCount() > 0) { GEN.selMoveOther({target_layer:drl_slot_tmp,invert:'no',dx:0,dy:0,size:0}) }
		var syms = GEN.getLayerSymsHist({job:job,step:step,layer:drl,units:units})
		var drl_pre1s = [];
		var drl_pre2s = [];
		var drl_pre3s = [];
		var drl_pre4s = [];
		var slots = [];
		for (var key in syms) {
			if (/r\d/.test(key)) {
				var size = parseFloat(key.slice(1)) 
				if( size >= 4050 && size <= 5050 ) {
					drl_pre1s.push(key)
				} else if ( size >= 5100 && size <= 6000 ) {
					drl_pre2s.push(key)
				} else if ( size >= 6050 && size <= 9000 ) {
					drl_pre3s.push(key)
				} else if ( size >= 9050 && size <= 12000 ) {
					drl_pre4s.push(key)
				}
			} else {
				slots.push(key)
			}
		}
		if (slots.length) {
			GEN.selectByFilter({include_syms:slots.join(";")})
			if(GEN.getSelectCount() > 0) {
				GEN.selMoveOther({target_layer:drl_slot_tmp,invert:'no',dx:0,dy:0,size:0})
			}
		}

		// 1. 槽孔处理  1、槽孔：槽长和槽宽的比≤1.8时需按以下要求添加，添加位置，预钻孔边与槽端相切，预钻孔圆心在槽孔中心线上；取值大小，d=L/2，选刀方式最大化，进位取整 ；分刀，加0.001结尾用于区分普通孔；
		if (GEN.isLayerExists({job:job, layer:drl_slot_tmp})) {
			GEN.workLayer({name:drl_slot_tmp,display_number:2,clear_before:'yes'})
			// 计算每个孔的槽长槽宽比
			var feats = GEN.getFeatures({job:job,step:step,layer:drl_slot_tmp,units:units})
			feats.forEach(function(feat) {
				GEN.selClearFeature()
				if(feat.type == "line"){
					GEN.COM("sel_net_feat,operation=select,x="+feat.xs+",y="+feat.ys+",use_ffilter=no")
				} else if (feat.type == "pad") {
					GEN.COM("sel_net_feat,operation=select,x="+feat.x+",y="+feat.y+",use_ffilter=no")
				}
				if(GEN.getSelectCount() == 1) {
					GEN.selClearFeature()
					if( feat.type == "line") {
						var width = parseFloat(feat.symbol.slice(1));
						var d = Math.sqrt( (feat.xe - feat.xs)*(feat.xe - feat.xs) + (feat.ye - feat.ys)*(feat.ye - feat.ys) )*1000 + width;
						var k = d/width;
						if ( k <= 1.8) {
							// 1. 计算预钻孔 直径
							var r =  Math.round((width / 2)/ 50 ) * 50 + 1;
							// 2. 计算槽孔两个端点坐标  计算两个槽孔向内缩短 r/2 后的坐标   // 算法  已知 线段两个端点 一个函数 输入 正负数 算出线段两端加上或者减去输入的值后的端点
							var ret = changeLine(feat, (width-r)/2000)
							// 3. 以算出的坐标为中心 r 为symbol 画预钻孔
							GEN.addPad({x:ret.xe,y:ret.ye,symbol:'r' + r,attributes:[{attribute:".string", text:"_pre_drl"}]})
							GEN.addPad({x:ret.xs,y:ret.ys,symbol:'r' + r,attributes:[{attribute:".string", text:"_pre_drl"}]})
						}
					}
				}
				GEN.selClearFeature()
			})
			GEN.selMoveOther({target_layer:drl,invert:'no',dx:0,dy:0,size:0})
		}

		// 2. drl_pre1s
		if(drl_pre1s.length) {
			GEN.workLayer({name:drl,display_number:2,clear_before:'yes'})
			GEN.selectByFilter({include_syms:drl_pre1s.join(";")})
			if(GEN.getSelectCount() > 0) { 
				GEN.selMoveOther({target_layer:drl_pre1,invert:'no',dx:0,dy:0,size:0}) 
				GEN.workLayer({name:drl_pre1,display_number:2,clear_before:'yes'})
				var feats = GEN.getFeatures({job:job,step:step,layer:drl_pre1,units:units})
				feats.forEach(function(feat) {
					GEN.selClearFeature()
					if(feat.type == "line"){
						GEN.COM("sel_net_feat,operation=select,x="+feat.xs+",y="+feat.ys+",use_ffilter=no")
					} else if (feat.type == "pad") {
						GEN.COM("sel_net_feat,operation=select,x="+feat.x+",y="+feat.y+",use_ffilter=no")
					}
					if(GEN.getSelectCount() == 1) {
						GEN.selClearFeature()
						var x = Number(feat.x)
						var y = Number(feat.y)
						GEN.addPad({x:x,y:y,symbol:'r1001',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x + 1.301,y:y,symbol:'r1001',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x - 1.301,y:y,symbol:'r1001',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y + 1.301,symbol:'r1001',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y - 1.301,symbol:'r1001',attributes:[{attribute:".string", text:"_pre_drl"}]})
					}
					GEN.selClearFeature()
				})
			}
			GEN.selMoveOther({target_layer:drl,invert:'no',dx:0,dy:0,size:0})
		}

		// 2. drl_pre2s
		if(drl_pre2s.length) {
			GEN.workLayer({name:drl,display_number:2,clear_before:'yes'})
			GEN.selectByFilter({include_syms:drl_pre2s.join(";")})
			if(GEN.getSelectCount() > 0) { 
				GEN.selMoveOther({target_layer:drl_pre2,invert:'no',dx:0,dy:0,size:0}) 
				GEN.workLayer({name:drl_pre2,display_number:2,clear_before:'yes'})
				var feats = GEN.getFeatures({job:job,step:step,layer:drl_pre2,units:units})
				feats.forEach(function(feat) {
					GEN.selClearFeature()
					if(feat.type == "line"){
						GEN.COM("sel_net_feat,operation=select,x="+feat.xs+",y="+feat.ys+",use_ffilter=no")
					} else if (feat.type == "pad") {
						GEN.COM("sel_net_feat,operation=select,x="+feat.x+",y="+feat.y+",use_ffilter=no")
					}
					if(GEN.getSelectCount() == 1) {
						GEN.selClearFeature()
						var x = Number(feat.x)
						var y = Number(feat.y)
						GEN.addPad({x:x,y:y,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x + 1.601,y:y,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x - 1.601,y:y,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y + 1.601,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y - 1.601,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
					}
					GEN.selClearFeature()
				})
			}
			GEN.selMoveOther({target_layer:drl,invert:'no',dx:0,dy:0,size:0})
		}

		// 3. drl_pre3s
		if(drl_pre3s.length) {
			GEN.workLayer({name:drl,display_number:2,clear_before:'yes'})
			GEN.selectByFilter({include_syms:drl_pre3s.join(";")})
			if(GEN.getSelectCount() > 0) { 
				GEN.selMoveOther({target_layer:drl_pre3,invert:'no',dx:0,dy:0,size:0}) 
				GEN.workLayer({name:drl_pre3,display_number:2,clear_before:'yes'})
				var feats = GEN.getFeatures({job:job,step:step,layer:drl_pre3,units:units})
				feats.forEach(function(feat) {
					GEN.selClearFeature()
					if(feat.type == "line"){
						GEN.COM("sel_net_feat,operation=select,x="+feat.xs+",y="+feat.ys+",use_ffilter=no")
					} else if (feat.type == "pad") {
						GEN.COM("sel_net_feat,operation=select,x="+feat.x+",y="+feat.y+",use_ffilter=no")
					}
					if(GEN.getSelectCount() == 1) {
						GEN.selClearFeature()
						var x = Number(feat.x)
						var y = Number(feat.y)
						GEN.addPad({x:x,y:y,symbol:'r3001',attributes:[{attribute:".string", text:"_pre_drl"}]})
					}
					GEN.selClearFeature()
				})
			}
			GEN.selMoveOther({target_layer:drl,invert:'no',dx:0,dy:0,size:0})
		}

		// 4. drl_pre4s
		if(drl_pre4s.length) {
			GEN.workLayer({name:drl,display_number:2,clear_before:'yes'})
			GEN.selectByFilter({include_syms:drl_pre4s.join(";")})
			if(GEN.getSelectCount() > 0) { 
				GEN.selMoveOther({target_layer:drl_pre4,invert:'no',dx:0,dy:0,size:0}) 
				GEN.workLayer({name:drl_pre4,display_number:2,clear_before:'yes'})
				var feats = GEN.getFeatures({job:job,step:step,layer:drl_pre4,units:units})
				feats.forEach(function(feat) {
					GEN.selClearFeature()
					if(feat.type == "line"){
						GEN.COM("sel_net_feat,operation=select,x="+feat.xs+",y="+feat.ys+",use_ffilter=no")
					} else if (feat.type == "pad") {
						GEN.COM("sel_net_feat,operation=select,x="+feat.x+",y="+feat.y+",use_ffilter=no")
					}
					if(GEN.getSelectCount() == 1) {
						GEN.selClearFeature()
						var x = Number(feat.x)
						var y = Number(feat.y)
						GEN.addPad({x:x,y:y,symbol:'r6001',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x + 1.601,y:y,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x - 1.601,y:y,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y + 1.601,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
						GEN.addPad({x:x,y:y - 1.601,symbol:'r1301',attributes:[{attribute:".string", text:"_pre_drl"}]})
					}
					GEN.selClearFeature()
				})
			}
			GEN.selMoveOther({target_layer:drl,invert:'no',dx:0,dy:0,size:0})
		}


		delIfExist(layers_tmp)
		})
		
	})




	// 保存 
	if(/yes/ig.test(par.auto_save)){GEN.checkInout({job:job,mode:"out"}); GEN.saveJob({ job: job });GEN.checkInout({job:job,mode:"in"});GEN.closeJob({job:job});} else {GEN.checkInout({job:job,mode:"in"})}
	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) { Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else { resultData.push({ type: "info", title: "操作完成, 请注意检查!" }); return {status: Status,result_data: resultData}; }
	}else { return "Done" }
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"));IKM.msg(e);Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function delIfExist(layer) {
	if(!Array.isArray(layer)){
		layer = [layer];
	}
	layer.forEach(function(l){
		if(GEN.isLayerExists({job:job, layer:l})){
			GEN.deleteLayer({job:job, layer:[l]})
		}
	})
}

function changeLine(line, length) {
    line.xs = Number(line.xs)
    line.ys = Number(line.ys)
    line.xe = Number(line.xe)
    line.ye = Number(line.ye)
    if (line.xe - line.xs == 0 || line.ye - line.ys == 0) {
        if (line.xe - line.xs == 0 ) {
            return {
                xs: line.xs,
                ys: line.ys + (line.ye - line.ys > 0 ? -length : length),
                xe: line.xe,
                ye: line.ye + (line.ye - line.ys > 0 ? length : -length)
            }
        } else {
            return {
                xs: line.xs - (line.xe - line.xs > 0 ? length : -length),
                ys: line.ys,
                xe: line.xe - (line.xe - line.xs > 0 ? -length : length),
                ye: line.ye
            }
        }
    }
    var width =  Math.sqrt( (line.xe - line.xs)*(line.xe - line.xs) + (line.ye - line.ys)*(line.ye - line.ys) )
    var k = length / width;
    var x = line.xe - line.xs;
    var y = line.ye - line.ys;
    return {
        xs: line.xs - k * x,
        ys: line.ys - k * y,
        xe: line.xe + k * x,
        ye: line.ye + k * y
    }
}